package cn.com.lms.business.exam.web;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.exam.persistence.entity.Exercise;
import cn.com.lms.business.exam.persistence.entity.ExerciseEmployee;
import cn.com.lms.business.exam.persistence.entity.ExerciseVO;
import cn.com.lms.business.exam.service.ExerciseDepartJobInfoService;
import cn.com.lms.business.exam.service.ExerciseEmployeeService;
import cn.com.lms.business.exam.service.ExerciseQuestionService;
import cn.com.lms.business.exam.service.ExerciseService;

import cn.com.lms.business.exam.web.vo.DepartJobInfoVO;
import cn.com.lms.business.exam.web.vo.ExerciseDetailVO;
import cn.com.lms.business.exam.web.vo.ExerciseEditorVO;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.cloud.business.core.persistence.entity.SysUser;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;

import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author zhangzhenjiang
 * @createDate 2020/3/16
 * @description
 */
@Tag(name = "练习", description = "题库练习管理")
@RestController
@RequestMapping("/exam/exercise")
public class  ExerciseController {

    @Autowired
    ExerciseService exerciseService;

    @Autowired
    ExerciseQuestionService exerciseQuestionService;
    @Autowired
    ExerciseEmployeeService exerciseEmployeeService;

    @Autowired
    ExerciseDepartJobInfoService exerciseDepartJobInfoService;


    @Operation(summary = "分页查询", description = "",parameters = {
            @Parameter(name = "keyWord", description = "关键子查询，题库名称进行模糊查询", allowEmptyValue = true,
                    allowReserved = true, schema = @Schema(implementation = String.class, description = "keyWord")),
            @Parameter(name = "limit", description = "分页大小", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "分页大小")),
            @Parameter(name = "offset", description = "页码", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "页码")),
    })
    @GetMapping(value = "/page")
    public ResponseResult<Page<ExerciseVO>> getExercisePage(HttpServletRequest request) {

        String keyWord = request.getParameter("keyWord");
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "ee.create_time"));
        QueryHelpBean queryHelpBean = ExerciseService.getQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        //试卷名称，模糊搜索
        if (StringHelper.isNotEmpty(keyWord)) {
            IExpression orCondition2 = CompareExpression.build("ee.exercise_name", CompareType.like, keyWord);
            queryHelpBean.addWhere(orCondition2);
        }
         IExpression andCondition1 = CompareExpression.build("ee.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(andCondition1);
        Page<ExerciseVO> all = exerciseService.findAll(queryHelpBean);
        return ResponseResult.success(all);
    }

    @Operation(summary = "根据id查询",description = "练习编辑")
    @GetMapping("/one/{id}")
    public ResponseResult<ExerciseEditorVO> getById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<Exercise> exerciseOpt = exerciseService.findById(id);
        if (!exerciseOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        Exercise exercise=exerciseOpt.get();
        ExerciseEditorVO exerciseVO=new ExerciseEditorVO();
        BeanUtils.copyProperties(exercise,exerciseVO);
        List<ExerciseEmployee> exerciseEmployees=  exerciseDepartJobInfoService.findExerciseEmployeeListByExerciseId(exercise.getId());
        List<DepartJobInfoVO> departJobInfoVOList= exerciseDepartJobInfoService.findDepartJobInfoVOByExerciseId(exercise.getId());
        List<Map> questionList=exerciseQuestionService.findQuestionByExerciseId(exercise.getId());
        List<Map> employeeList=exerciseEmployeeService.findEmployeeByExerciseId(exercise.getId());
        List<Map> removeList=new CopyOnWriteArrayList<>();
        if(!CollectionUtils.isEmpty(exerciseEmployees)){
            exerciseEmployees.stream().forEach(exerciseEmployee -> {
                removeList.addAll(employeeList.stream().filter(map -> exerciseEmployee.getEmployeeId()==((Number)map.get("employeeId")).longValue()).collect(Collectors.toList()));
            });
        }
        employeeList.removeAll(removeList);
        exerciseVO.setQuestionList(questionList);
        exerciseVO.setEmployeeList(employeeList);
        exerciseVO.setDepartJobInfo(departJobInfoVOList);
        return ResponseResult.success(exerciseVO);
    }

    @Operation(summary = "根据id查询",description = "查看练习详情人员列表")
    @GetMapping("/detail/{id}")
    public ResponseResult< List<Map>> getDetailById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {

        List<Map> employeeMaplist= exerciseEmployeeService.findEmployeeByExerciseId(id);

        return ResponseResult.success(employeeMaplist);
    }


    @Operation(summary = "导出", description = "导出练习详情人员列表", parameters = {
            @Parameter(name = "exerciseId", description = "练习ID", allowEmptyValue = false,
                    allowReserved = true, schema = @Schema(implementation = Long.class, description = "exerciseId")),
    })
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportExcel(@RequestParam(name = "exerciseId") Long exerciseId, HttpServletResponse response) {
        List<Map> employeeMaplist= exerciseEmployeeService.findEmployeeByExerciseId(exerciseId);
        HSSFWorkbook hssfWorkbook = exerciseEmployeeService.exportExerciseEmployeeListById(exerciseId,employeeMaplist);
        response.setContentType("application/octet-stream");
        //默认Excel名称
        response.setHeader("Content-Disposition", "attachment;fileName="+"测试练习-"+exerciseId+".xls");

        try {
            response.flushBuffer();
            hssfWorkbook.write(response.getOutputStream());
        } catch (IOException e) {
//            e.printStackTrace();
        }

    }



    @Operation(summary = "保存")
    @PostMapping("/save")
    public ResponseResult<?> addExercise(@RequestBody Exercise exercise) {
        List<ExerciseEmployee> exerciseEmployeeByDepartJobList=  exerciseDepartJobInfoService.findExerciseEmployeeList(exercise.getDepartJobInfo());
        List<ExerciseEmployee> exerciseEmployeeList=  exercise.getExerciseEmployeeList();

        List<ExerciseEmployee> listAll = new ArrayList<ExerciseEmployee>();
        if(!CollectionUtils.isEmpty(exerciseEmployeeByDepartJobList)) {
            listAll.addAll(exerciseEmployeeByDepartJobList);
        }
        if(!CollectionUtils.isEmpty(exerciseEmployeeList)) {
            listAll.addAll(exerciseEmployeeList);
        }
        listAll = new ArrayList<ExerciseEmployee>(new LinkedHashSet<>(listAll));
        exercise.setExerciseEmployeeList(listAll);

        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        exercise.setCreator(String.valueOf(sysUser.getId()));
        exercise.setCreateTime(new Date());
        exercise.setCreatorName(sysUser.getCname());
        exercise.setIsDelete(false);
        exercise.setIsEnable(false);
        exerciseService.addExercise(exercise);
        return ResponseResult.success();
    }


    @Operation(summary = "更新")
    @PostMapping("/update")
    public ResponseResult<?> updateExercise(@RequestBody Exercise exercise) {
        if (ObjectUtils.isEmpty(exercise.getId())) {
            throw new BusinessException(ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getMessage(), "" + ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getCode());
        }

        Optional<Exercise> exerciseOpt = exerciseService.findById(exercise.getId());
        if (!exerciseOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        Exercise target = exerciseOpt.get();
        List<ExerciseEmployee> exerciseEmployeeByDepartJobList=  exerciseDepartJobInfoService.findExerciseEmployeeList(exercise.getDepartJobInfo());
        List<ExerciseEmployee> exerciseEmployeeList=  exercise.getExerciseEmployeeList();

        List<ExerciseEmployee> listAll = new ArrayList<ExerciseEmployee>();
        if(!CollectionUtils.isEmpty(exerciseEmployeeByDepartJobList)) {
            listAll.addAll(exerciseEmployeeByDepartJobList);
        }
        if(!CollectionUtils.isEmpty(exerciseEmployeeList)) {
            listAll.addAll(exerciseEmployeeList);
        }
        listAll = new ArrayList<ExerciseEmployee>(new LinkedHashSet<>(listAll));
        exercise.setExerciseEmployeeList(listAll);

        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        exercise.setModifyTime(new Date());
        exercise.setModifyBy(String.valueOf(sysUser.getId()));
        exercise.setModifyName(sysUser.getCname());
        BeanUtils.copyProperties(exercise, target);

        exerciseService.updateExercise(target);
        return ResponseResult.success();
    }


    @Operation(summary = "删除，批量删除", description = "根据分类id删除试题")
    @PostMapping("/delete")
    public ResponseResult<Integer> deleteById(@RequestBody List<Long> id) {
        Integer count = exerciseService.updateIsDelete(true, id);
        return ResponseResult.success(count);

    }


    @Operation(summary = "启用", description = "根据分类id启用试卷")
    @PostMapping("/enable")
    public ResponseResult<Integer> enableById(@RequestBody List<Long> id) {
        Integer count = exerciseService.updateIsEnable(true, id);
        return ResponseResult.success(count);

    }
    @Operation(summary = "禁用", description = "根据分类id禁用试卷")
    @PostMapping("/disable")
    public ResponseResult<Integer> disableById(@RequestBody List<Long> id) {
        Integer count = exerciseService.updateIsEnable(false, id);
        return ResponseResult.success(count);

    }

}
